import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:music_app/api/real_api.dart';
import 'package:music_app/controllers/audio_player_controller.dart';
import 'package:music_app/widget/lyrics_widget.dart';
import 'package:music_app/widget/my_cached_network_image.dart';
import 'dart:math' as math;

class FullPlayer extends StatefulWidget {
  const FullPlayer({super.key});

  @override
  State<FullPlayer> createState() => _FullPlayerState();
}

class _FullPlayerState extends State<FullPlayer>
    with SingleTickerProviderStateMixin {
  List<LyricLine> lyrics = [];
  // 音乐播放控制器
  final audioController = Get.find<AudioPlayerController>();
  // 切换显示cd歌词
  // bool showLyrics = false;
  // 旋转动画控制器(使用这个类要 with SingleTickerProviderStateMixin类)
  late AnimationController _rotationController;
  // 旋转动画控制器
  @override
  void initState() {
    super.initState();
    // 初始化动画控制器
    _rotationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 20),
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getData();
    });
  }

  Future<void> getData() async {
    try {
      final id = audioController.currentSongId;
      final response = await RealApi.getLyric(id ?? 1468115100);
      var textList = parseLyrics(response['lrc']['lyric']);
      setState(() {
        lyrics = textList;
      });
    } catch (e) {
      setState(() {
        lyrics = [];
      });
    } finally {}
  }

  // 将歌词字符串 处理成数组
  List<LyricLine> parseLyrics(String rawLyrics) {
    final regex = RegExp(r'\[(\d{2}):(\d{2})\.(\d{1,3})\](.*)');
    final lines = rawLyrics.split('\n');
    return lines
        .map(
          (line) {
            final match = regex.firstMatch(line);
            if (match != null) {
              final minutes = int.parse(match.group(1)!);
              final seconds = int.parse(match.group(2)!);
              final millis =
                  int.parse(match.group(3)!.padRight(3, '0')); // 补足为 3 位
              final text = match.group(4)!.trim();

              return LyricLine(
                Duration(
                    minutes: minutes, seconds: seconds, milliseconds: millis),
                text,
              );
            }
            return null;
          },
        )
        .whereType<LyricLine>()
        .toList();
  }

  String _formatDuration(Duration d) {
    final minutes = d.inMinutes.toString().padLeft(2, '0');
    final seconds = (d.inSeconds % 60).toString().padLeft(2, '0');
    return '$minutes:$seconds';
  }

  IconData _buildLoopIcon(PlayMode mode) {
    switch (mode) {
      case PlayMode.loop:
        return Icons.repeat;
      case PlayMode.single:
        return Icons.repeat_one;
      case PlayMode.shuffle:
        return Icons.shuffle;
      default:
        return Icons.repeat;
    }
  }

  // 卸载移除动画实例
  @override
  void dispose() {
    _rotationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double width = (MediaQuery.of(context).size.width) - 100;
    return Obx(
      () {
        final song = audioController.currentSong;
        if (audioController.isPlaying.value) {
          _rotationController.repeat();
        } else {
          _rotationController.stop();
        }
        return Scaffold(
          backgroundColor: const Color(0xFFF9F9F9),
          body: SafeArea(
            child: Column(
              children: [
                // 顶部栏
                Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 8,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      IconButton(
                        icon: const Icon(
                          Icons.arrow_downward,
                          size: 24,
                        ),
                        onPressed: () => Get.back(),
                      ),
                      const Text(
                        '正在播放',
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                      IconButton(
                        icon: const Icon(
                          Icons.open_in_new,
                          size: 24,
                        ),
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
                // cd 歌词滚动 区域 Expanded组件 占掉其他固定高度后的剩下的所以区域
                // Expanded(
                //   child: GestureDetector(
                //     onTap: () => setState(() => showLyrics = !showLyrics),
                //     child: AnimatedSwitcher(
                //       // 切换淡入淡出动画
                //       duration: const Duration(milliseconds: 300),
                //       child: showLyrics
                //           ? SizedBox(
                //               child: Padding(
                //               padding: const EdgeInsets.only(
                //                 left: 24,
                //                 right: 24,
                //               ),
                //               child: LyricWidget(
                //                 lyrics: lyrics,
                //                 currentPosition: audioController.position.value,
                //               ),
                //             ))
                //           : Container(
                //               // 之所以使用Container 不适应SizedBox 因为Container能点击GestureDetector的点击事件 但是SizedBox不可以 暂时不知道为什么
                //               height: double.infinity,
                //               width: double.infinity,
                //               decoration: const BoxDecoration(
                //                 color: Color(0xFFF9F9F9),
                //               ),
                //               child: Column(
                //                 mainAxisAlignment: MainAxisAlignment.center,
                //                 children: [
                //                   Container(
                //                     width: width,
                //                     height: width,
                //                     decoration: BoxDecoration(
                //                       shape: BoxShape.circle,
                //                       border: Border.all(
                //                         color: Colors.black,
                //                         width: 30,
                //                       ),
                //                     ),
                //                     child: AnimatedBuilder(
                //                       animation: _rotationController,
                //                       builder: (_, child) {
                //                         return Transform.rotate(
                //                           angle: _rotationController.value *
                //                               2 *
                //                               math.pi,
                //                           child: ClipRRect(
                //                             borderRadius:
                //                                 BorderRadius.circular(width),
                //                             child: MyCachedNetworkImage(
                //                               imageUrl: song['al']['picUrl'],
                //                               width: 200,
                //                               height: 200,
                //                               x: 720,
                //                               y: 720,
                //                             ),
                //                           ),
                //                         );
                //                       },
                //                     ),
                //                   ),
                //                 ],
                //               ),
                //             ),
                //     ),
                //   ),
                // ),
                Expanded(
                  // 使用pageview切换
                  child: PageView(
                    children: [
                      Container(
                        // 之所以使用Container 不适应SizedBox 因为Container能点击GestureDetector的点击事件 但是SizedBox不可以 暂时不知道为什么
                        height: double.infinity,
                        width: double.infinity,
                        decoration: const BoxDecoration(
                          color: Color(0xFFF9F9F9),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: width,
                              height: width,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                border: Border.all(
                                  color: Colors.black,
                                  width: 30,
                                ),
                              ),
                              child: AnimatedBuilder(
                                animation: _rotationController,
                                builder: (_, child) {
                                  return Transform.rotate(
                                    angle:
                                        _rotationController.value * 2 * math.pi,
                                    child: ClipRRect(
                                      borderRadius:
                                          BorderRadius.circular(width),
                                      child: MyCachedNetworkImage(
                                        imageUrl: song['al']['picUrl'],
                                        width: 200,
                                        height: 200,
                                        x: 720,
                                        y: 720,
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        child: Padding(
                          padding: const EdgeInsets.only(
                            left: 24,
                            right: 24,
                          ),
                          child: LyricWidget(
                            lyrics: lyrics,
                            currentPosition: audioController.position.value,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                // 歌曲名和作者
                Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 24,
                    vertical: 12,
                  ),
                  child: Column(
                    children: [
                      Text(
                        song['name'],
                        style: const TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold),
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      Text(
                        (song['ar'] as List).map((a) => a['name']).join(', '),
                        style: const TextStyle(color: Colors.grey),
                      ),
                    ],
                  ),
                ),
                // 进度条
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  child: Column(
                    children: [
                      Slider(
                        value:
                            audioController.position.value.inSeconds.toDouble(),
                        max:
                            audioController.duration.value.inSeconds.toDouble(),
                        onChanged: (value) {
                          // 修改进度条 改变音乐实例里的进度
                          audioController
                              .seekTo(Duration(seconds: value.toInt()));
                        },
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 18),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              _formatDuration(audioController.position.value),
                              style: const TextStyle(
                                fontSize: 12,
                                color: Colors.black,
                              ),
                            ),
                            Text(
                              _formatDuration(audioController.duration.value),
                              style: const TextStyle(
                                fontSize: 12,
                                color: Colors.black,
                              ),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                // 播放控制按钮
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 24),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      IconButton(
                        icon: Icon(
                            _buildLoopIcon(audioController.playMode.value)),
                        onPressed: () => audioController.changePlayMode(),
                      ),
                      IconButton(
                        icon: const Icon(Icons.skip_previous),
                        iconSize: 32,
                        onPressed: () => audioController.playPrevious(),
                      ),
                      IconButton(
                        icon: Icon(audioController.isPlaying.value
                            ? Icons.pause_circle
                            : Icons.play_circle),
                        iconSize: 64,
                        onPressed: () => audioController.togglePlayPause(),
                      ),
                      IconButton(
                        icon: const Icon(Icons.skip_next),
                        iconSize: 32,
                        onPressed: () => audioController.playNext(),
                      ),
                      IconButton(
                        icon: const Icon(Icons.queue_music),
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 32),
              ],
            ),
          ),
        );
      },
    );
  }
}
